package com.sgj.gulimall.ware.listener;

import com.rabbitmq.client.Channel;
import com.sgj.common.to.mq.OrderTo;
import com.sgj.common.to.mq.StockLockedTo;
import com.sgj.gulimall.ware.service.WareSkuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @Author: Guoji Shen
 * @Date: 2021/10/26 9:38
 */
@Slf4j
@Service
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {

    @Autowired
    private WareSkuService wareSkuService;

    /**
     * 释放锁定内存
     * @param to
     * @param message
     */
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
        log.info("[StockReleaseListener][handleStockLockedRelease] 收到解锁库存的消息");
        try {
            wareSkuService.unLockStock(to);
            // 消费消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            // 拒绝消息，并将该消息返回到队列中
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

    @RabbitHandler
    public void handleOrderCloseRelease(OrderTo to, Message message, Channel channel) throws IOException {
        log.info("[StockReleaseListener][handleOrderCloseRelease] 订单关闭,准备解锁库存");
        try {
            wareSkuService.unLockStock(to);
            // 消费消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            // 拒绝消息，并将该消息返回到队列中
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}